<script setup>
import { ref, getCurrentInstance } from 'vue'
import { addUser, updateUser, getUserById } from '@/api/user'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { userStore } from '@/stores/loginStore'
const userInfo = userStore()
//获取当前Vue实例
const instance = getCurrentInstance()
const userForm = ref({
  userId: '',
  userName: '',
  password: '',
  nickName: '',
  avatar: '',
  gender: '',
  phone: '',
  status: ''
})
const dialogVisible = ref(false)
const title = ref('')
// 图片上传
let token = ref('')
token.value = userInfo.token
//上传成功后调用的方法
const handleAvatarSuccess = (
  response,
  uploadFile,
) => {
  userForm.value.avatar = response.data
}
//上传前校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('图片格式必须是 png 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不得超过 2MB!')
    return false
  }
  return true
}
//校验
const rules = ref({
  userName: [
    { required: true, message: '名称不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '长度3-10', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '长度3-10', trigger: 'blur' },
  ],
  nickName: [
    { required: true, message: '名称不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '长度3-10', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { max: 11, message: '超出长度11位', trigger: 'blur' },
  ],
  gender:[
    { required: true, message: '性别不能为空', trigger: 'blur' },
  ],
})
//绑定表单
const userFormRef = ref()
const submitForm = async () => {
  if (!userFormRef) return
  await userFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let result = null
      if (userForm.value.userId) {
        result = await updateUser(userForm.value.userId, userForm.value)
        if (result.code == 200) {
          ElMessage.success("修改成功")
          instance.emit('search')
          dialogVisible.value = false
        } else {
          ElMessage.error("修改失败")
        }
      } else {
        result = await addUser(userForm.value)
        if (result.code == 200) {
          ElMessage.success("新增成功")
          instance.emit('search')
          dialogVisible.value = false
        } else {
          ElMessage.error("新增失败")
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// let result = await updateUser(row.id, row)
// 
// }
const cancel = () => {
  dialogVisible.value = false
  userForm.value = {}
  instance.emit('search')
}

// 暴露给父组件的变量和方法
defineExpose({
  // 暴露参数
  dialogVisible,
  userForm,
  title,
  submitForm,
  // 暴露方法
  show(val) {
    dialogVisible.value = val
  }
})
</script>
<template>
  <el-dialog v-model="dialogVisible" :title="title" width="500">
    <el-form ref="userFormRef" :rules="rules" :model="userForm" label-width="auto" style="max-width: 600px">
      <el-form-item label="账号：" prop="userName">
        <el-input v-model="userForm.userName" style="width: 200px;" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="userForm.password" style="width: 200px;" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="昵称：" prop="nickName">
        <el-input v-model="userForm.nickName" style="width: 200px;" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="性别：" prop="gender">
        <el-select v-model="userForm.gender" style="width: 200px;" placeholder="请选择性别">
          <el-option label="男" value="1" />
          <el-option label="女" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号：" prop="phone">
        <el-input v-model="userForm.phone" style="width: 240px" maxlength="11" placeholder="请输入手机号" show-word-limit
          type="text" />
        <!-- <el-input v-model="userForm.phone" style="width: 200px;" /> -->
      </el-form-item>
      <el-form-item label="头像：" prop="image">
        <el-upload class="avatar-uploader" action="/api/upload" :headers="{ 'token': token }" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <template #label>
          <span>请选择状态：</span>
        </template>
        <el-radio-group label="状态：" v-model="userForm.status">
          <el-radio-button label="启用" value="1">启用</el-radio-button>
          <el-radio-button label="禁用" value="0">禁用</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>